import React, { useState, useEffect } from 'react'
import toast from 'react-hot-toast'
import {
  Plus,
  Trash2,
  Edit,
  Settings,
  Database,
  Users,
  Clock,
  AlertCircle,
  CheckCircle,
  RefreshCw
} from 'lucide-react'
import { useKafkaStore } from '@/stores/kafkaStore'
import { kafkaApi } from '@/services/kafka'

// 类型定义
interface TopicConfig {
  cleanup_policy: string
  retention_ms: number
  retention_bytes: number
  segment_ms: number
  segment_bytes: number
  max_message_bytes: number
  min_insync_replicas: number
  compression_type: string
  delete_retention_ms: number
  file_delete_delay_ms: number
  flush_messages: number
  flush_ms: number
  index_interval_bytes: number
  max_compaction_lag_ms: number
  message_downconversion_enable: boolean
  message_format_version: string
  message_timestamp_type: string
  preallocate: boolean
  unclean_leader_election_enable: boolean
}

interface TopicConfigForm {
  cleanup_policy: string
  retention_ms: string
  retention_bytes: string
  segment_ms: string
  segment_bytes: string
  max_message_bytes: string
  min_insync_replicas: string
  compression_type: string
  delete_retention_ms: string
  file_delete_delay_ms: string
  flush_messages: string
  flush_ms: string
  index_interval_bytes: string
  max_compaction_lag_ms: string
  message_downconversion_enable: boolean
  message_format_version: string
  message_timestamp_type: string
  preallocate: boolean
  unclean_leader_election_enable: boolean
}

interface TopicInfo {
  name: string
  partitions: number
  replication_factor: number
  config: Record<string, any>
  created_time?: string
}

interface CreateTopicRequest {
  name: string
  partitions: number
  replication_factor: number
  config?: TopicConfig
}

const TopicManager: React.FC = () => {
  const [topics, setTopics] = useState<TopicInfo[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // 搜索和分页状态
  const [searchTerm, setSearchTerm] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)

  // Kafka连接状态管理
  const { setConnectionStatus } = useKafkaStore()
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [showConfigModal, setShowConfigModal] = useState(false)
  const [selectedTopic, setSelectedTopic] = useState<string | null>(null)
  const [selectedTopicConfig, setSelectedTopicConfig] = useState<TopicInfo | null>(null)
  const [isEditingConfig, setIsEditingConfig] = useState(false)
  const [configError, setConfigError] = useState<any>(null)
  const [configForm, setConfigForm] = useState<TopicConfigForm>({
    cleanup_policy: 'delete',
    retention_ms: '604800000',
    retention_bytes: '-1',
    segment_ms: '604800000',
    segment_bytes: '1073741824',
    max_message_bytes: '1000012',
    min_insync_replicas: '1',
    compression_type: 'producer',
    delete_retention_ms: '86400000',
    file_delete_delay_ms: '60000',
    flush_messages: '9223372036854775807',
    flush_ms: '9223372036854775807',
    index_interval_bytes: '4096',
    max_compaction_lag_ms: '9223372036854775807',
    message_downconversion_enable: true,
    message_format_version: '3.0-IV1',
    message_timestamp_type: 'CreateTime',
    preallocate: false,
    unclean_leader_election_enable: false
  })
  const [createForm, setCreateForm] = useState<CreateTopicRequest>({
    name: '',
    partitions: 1,
    replication_factor: 1
  })
  const [brokerCount, setBrokerCount] = useState<number>(1)

  // 获取broker数量
  const loadBrokerCount = async () => {
    try {
      const response = await fetch('/api/kafka/cluster/info')
      if (response.ok) {
        const data = await response.json()
        const count = data.brokers?.length || 1
        setBrokerCount(count)
      }
    } catch (error) {
      console.error('获取broker数量失败:', error)
      setBrokerCount(1)
    }
  }

  // 过滤和分页逻辑
  const filteredTopics = topics.filter(topic =>
    topic.name.toLowerCase().includes(searchTerm.toLowerCase())
  )

  const totalPages = Math.ceil(filteredTopics.length / pageSize)
  const startIndex = (currentPage - 1) * pageSize
  const endIndex = startIndex + pageSize
  const paginatedTopics = filteredTopics.slice(startIndex, endIndex)

  // 高亮搜索词
  const highlightSearchTerm = (text: string, searchTerm: string) => {
    if (!searchTerm) return text

    const regex = new RegExp(`(${searchTerm})`, 'gi')
    const parts = text.split(regex)

    return parts.map((part, index) =>
      regex.test(part) ? (
        <span key={index} className="bg-yellow-200 text-yellow-800 px-1 rounded">
          {part}
        </span>
      ) : part
    )
  }

  // 加载Topic列表
  const loadTopics = async () => {
    try {
      setLoading(true)
      setError(null)

      const response = await fetch('/api/topic-manager/topics')
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }

      const data = await response.json()
      setTopics(data)
    } catch (err) {
      console.error('加载Topic列表失败:', err)
      setError(err instanceof Error ? err.message : '加载失败')
    } finally {
      setLoading(false)
    }
  }

  // 创建Topic
  const createTopic = async () => {
    try {
      setError(null)

      const response = await fetch('/api/topic-manager/topics', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(createForm)
      })

      if (!response.ok) {
        const errorData = await response.json()

        // 处理副本数错误的特殊情况
        if (response.status === 400 && typeof errorData.detail === 'object') {
          const detail = errorData.detail
          const errorMsg = `${detail.error}\n建议副本数: ${detail.suggested_replication_factor}\n当前broker数量: ${detail.broker_count}`
          throw new Error(errorMsg)
        }

        throw new Error(errorData.detail || `HTTP ${response.status}`)
      }

      const result = await response.json()
      console.log('Topic创建成功:', result)

      // 显示成功消息，包括警告信息
      if (result.warnings && result.warnings.length > 0) {
        toast.success(`${result.message}`, {
          duration: 6000,
          style: {
            background: '#FEF3C7',
            color: '#92400E',
            border: '1px solid #F59E0B'
          }
        })
      } else {
        toast.success(result.message)
      }

      // 重置表单并关闭模态框
      setCreateForm({
        name: '',
        partitions: 1,
        replication_factor: 1
      })
      setShowCreateModal(false)

      // 重新加载Topic列表
      await loadTopics()

    } catch (err) {
      console.error('创建Topic失败:', err)
      const errorMessage = err instanceof Error ? err.message : '创建失败'
      setError(errorMessage)
      toast.error(errorMessage)
    }
  }

  // 删除Topic
  const deleteTopic = async (topicName: string) => {
    try {
      setError(null)

      const response = await fetch(`/api/topic-manager/topics/${topicName}`, {
        method: 'DELETE'
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.detail || `HTTP ${response.status}`)
      }

      const result = await response.json()
      console.log('Topic删除成功:', result)

      setShowDeleteModal(false)
      setSelectedTopic(null)

      // 重新加载Topic列表
      await loadTopics()

    } catch (err) {
      console.error('删除Topic失败:', err)
      setError(err instanceof Error ? err.message : '删除失败')
    }
  }

  // 打开配置编辑模态框
  const openConfigModal = (topic: TopicInfo) => {
    setSelectedTopicConfig(topic)
    setShowConfigModal(true)
    setIsEditingConfig(false)

    // 初始化配置表单
    initializeConfigForm(topic)
  }

  // 关闭配置编辑模态框
  const closeConfigModal = () => {
    setShowConfigModal(false)
    setSelectedTopicConfig(null)
    setIsEditingConfig(false)
    setConfigError(null)
  }

  // 初始化配置表单
  const initializeConfigForm = (topic: TopicInfo) => {
    const config = topic.config || {}
    setConfigForm({
      cleanup_policy: config['cleanup.policy'] || 'delete',
      retention_ms: config['retention.ms'] || '604800000',
      retention_bytes: config['retention.bytes'] || '-1',
      segment_ms: config['segment.ms'] || '604800000',
      segment_bytes: config['segment.bytes'] || '1073741824',
      max_message_bytes: config['max.message.bytes'] || '1000012',
      min_insync_replicas: config['min.insync.replicas'] || '1',
      compression_type: config['compression.type'] || 'producer',
      delete_retention_ms: config['delete.retention.ms'] || '86400000',
      file_delete_delay_ms: config['file.delete.delay.ms'] || '60000',
      flush_messages: config['flush.messages'] || '9223372036854775807',
      flush_ms: config['flush.ms'] || '9223372036854775807',
      index_interval_bytes: config['index.interval.bytes'] || '4096',
      max_compaction_lag_ms: config['max.compaction.lag.ms'] || '9223372036854775807',
      message_downconversion_enable: config['message.downconversion.enable'] !== 'false',
      message_format_version: config['message.format.version'] || '3.0-IV1',
      message_timestamp_type: config['message.timestamp.type'] || 'CreateTime',
      preallocate: config['preallocate'] === 'true',
      unclean_leader_election_enable: config['unclean.leader.election.enable'] === 'true'
    })
  }

  // 更新Topic配置
  const updateTopicConfig = async () => {
    if (!selectedTopicConfig) return

    try {
      setConfigError(null)

      // 转换表单数据为API格式
      const configData = {
        config: {
          cleanup_policy: configForm.cleanup_policy,
          retention_ms: parseInt(configForm.retention_ms),
          retention_bytes: parseInt(configForm.retention_bytes),
          segment_ms: parseInt(configForm.segment_ms),
          segment_bytes: parseInt(configForm.segment_bytes),
          max_message_bytes: parseInt(configForm.max_message_bytes),
          min_insync_replicas: parseInt(configForm.min_insync_replicas),
          compression_type: configForm.compression_type,
          delete_retention_ms: parseInt(configForm.delete_retention_ms),
          file_delete_delay_ms: parseInt(configForm.file_delete_delay_ms),
          flush_messages: parseInt(configForm.flush_messages),
          flush_ms: parseInt(configForm.flush_ms),
          index_interval_bytes: parseInt(configForm.index_interval_bytes),
          max_compaction_lag_ms: parseInt(configForm.max_compaction_lag_ms),
          message_downconversion_enable: configForm.message_downconversion_enable,
          message_format_version: configForm.message_format_version,
          message_timestamp_type: configForm.message_timestamp_type,
          preallocate: configForm.preallocate,
          unclean_leader_election_enable: configForm.unclean_leader_election_enable
        }
      }

      const response = await fetch(`/api/topic-manager/topics/${selectedTopicConfig.name}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(configData)
      })

      if (!response.ok) {
        const errorData = await response.json()
        // 保存完整的错误信息用于在模态框中显示
        setConfigError(errorData.detail || `HTTP ${response.status}`)
        return
      }

      const result = await response.json()
      console.log('Topic配置更新成功:', result)

      setIsEditingConfig(false)

      // 重新加载Topic列表
      await loadTopics()

      // 更新当前显示的Topic信息
      const updatedTopics = await fetch('/api/topic-manager/topics').then(res => res.json())
      const updatedTopic = updatedTopics.find((t: TopicInfo) => t.name === selectedTopicConfig.name)
      if (updatedTopic) {
        setSelectedTopicConfig(updatedTopic)
        initializeConfigForm(updatedTopic)
      }

    } catch (err) {
      console.error('更新Topic配置失败:', err)
      setConfigError(err instanceof Error ? err.message : '更新配置失败')
    }
  }

  // 格式化字节大小
  const formatBytes = (bytes: number): string => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 格式化数字
  const formatNumber = (num: number): string => {
    if (num >= 1000000) {
      return (num / 1000000).toFixed(1) + 'M'
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'K'
    }
    return num.toString()
  }

  // 格式化时间（毫秒转换为可读格式）
  const formatTime = (ms: string): string => {
    const num = parseInt(ms)
    if (num === -1 || num === 9223372036854775807) return '无限制'
    if (num >= 86400000) return `${Math.floor(num / 86400000)}天`
    if (num >= 3600000) return `${Math.floor(num / 3600000)}小时`
    if (num >= 60000) return `${Math.floor(num / 60000)}分钟`
    return `${num}毫秒`
  }

  // 格式化字节大小
  const formatConfigBytes = (bytes: string): string => {
    const num = parseInt(bytes)
    if (num === -1) return '无限制'
    return formatBytes(num)
  }

  useEffect(() => {
    const initializeTopicManager = async () => {
      try {
        // 首先检测Kafka连接状态
        const connectionResult = await kafkaApi.testConnection()
        if (connectionResult.success) {
          setConnectionStatus('已连接', true)
          // 连接成功后加载Topic列表和broker信息
          await loadTopics()
          await loadBrokerCount()
        } else {
          setConnectionStatus('连接失败', false)
          console.warn('Kafka连接失败，请检查配置')
        }
      } catch (error) {
        console.error('初始化Topic管理失败:', error)
        setConnectionStatus('连接失败', false)
      }
    }

    initializeTopicManager()
  }, [setConnectionStatus])

  return (
    <div className="space-y-8">
      {/* 页面头部 */}
      <div className="flex flex-col lg:flex-row lg:justify-between lg:items-center space-y-4 lg:space-y-0">
        <div className="text-center lg:text-left">
          <h1 className="text-3xl font-bold gradient-text flex items-center justify-center lg:justify-start gap-3 mb-2">
            <Database className="w-8 h-8 text-primary-600" />
            Topic管理
          </h1>
          <p className="text-lg text-gray-600">
            管理Kafka Topic的创建、配置和删除
          </p>
        </div>
        <div className="flex flex-col sm:flex-row gap-3 justify-center lg:justify-end">
          <button
            onClick={loadTopics}
            disabled={loading}
            className="btn-outline hover-lift"
          >
            <RefreshCw className={`w-4 h-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
            刷新列表
          </button>
          <button
            onClick={() => setShowCreateModal(true)}
            className="btn-primary hover-lift"
          >
            <Plus className="w-4 h-4 mr-2" />
            创建Topic
          </button>
        </div>
      </div>

      {/* 错误提示 */}
      {error && (
        <div className="card border-red-200 bg-red-50">
          <div className="card-content">
            <div className="flex items-start space-x-3">
              <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" />
              <div>
                <h3 className="text-sm font-semibold text-red-800 mb-1">操作失败</h3>
                <p className="text-sm text-red-700">{error}</p>
              </div>
            </div>
          </div>
        </div>
      )}

        {/* Topic列表 */}
        <div className="card hover-lift">
          <div className="card-header">
            <div className="flex flex-col lg:flex-row lg:justify-between lg:items-center space-y-4 lg:space-y-0">
              <div>
                <h2 className="card-title">Topic列表</h2>
                <p className="card-description">
                  当前共有 <span className="font-semibold text-primary-600">{topics.length}</span> 个Topic，
                  显示 <span className="font-semibold text-green-600">{filteredTopics.length}</span> 个
                </p>
              </div>

              {/* 搜索和筛选区域 */}
              <div className="flex flex-col sm:flex-row items-stretch sm:items-center space-y-3 sm:space-y-0 sm:space-x-4">
                <div className="relative flex-1 max-w-md">
                  <input
                    type="text"
                    placeholder="搜索Topic名称..."
                    value={searchTerm}
                    onChange={(e) => {
                      setSearchTerm(e.target.value)
                      setCurrentPage(1) // 重置到第一页
                    }}
                    className="input w-full pr-10"
                  />
                  {searchTerm && (
                    <button
                      onClick={() => {
                        setSearchTerm('')
                        setCurrentPage(1)
                      }}
                      className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 text-lg"
                    >
                      ×
                    </button>
                  )}
                </div>

                {/* 每页显示数量选择 */}
                <div className="flex items-center space-x-2">
                  <label className="text-sm font-medium text-gray-700 whitespace-nowrap">
                    每页显示:
                  </label>
                  <select
                    value={pageSize}
                    onChange={(e) => {
                      setPageSize(Number(e.target.value))
                      setCurrentPage(1)
                    }}
                    className="input w-24"
                  >
                    <option value={5}>5条</option>
                    <option value={10}>10条</option>
                    <option value={20}>20条</option>
                    <option value={50}>50条</option>
                  </select>
                </div>
              </div>
            </div>
          </div>

          {loading ? (
            <div className="p-8 text-center">
              <RefreshCw className="w-8 h-8 animate-spin mx-auto text-gray-400" />
              <p className="mt-2 text-sm text-gray-500">加载中...</p>
            </div>
          ) : topics.length === 0 ? (
            <div className="p-8 text-center">
              <Database className="w-12 h-12 mx-auto text-gray-400" />
              <h3 className="mt-2 text-sm font-medium text-gray-900">暂无Topic</h3>
              <p className="mt-1 text-sm text-gray-500">
                点击"创建Topic"按钮来创建第一个Topic
              </p>
            </div>
          ) : (
            <div className="overflow-hidden">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Topic名称
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      分区数
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      副本数
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {paginatedTopics.map((topic) => (
                    <tr key={topic.name} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="flex items-center">
                          <div className="flex-shrink-0">
                            <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                              <Database className="w-4 h-4 text-blue-600" />
                            </div>
                          </div>
                          <div className="ml-4">
                            <div className="text-sm font-medium text-gray-900">
                              {highlightSearchTerm(topic.name, searchTerm)}
                            </div>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        {topic.partitions}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        {topic.replication_factor}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <div className="flex justify-end gap-2">
                          <button
                            onClick={() => openConfigModal(topic)}
                            disabled={true}
                            className="text-blue-600 hover:text-blue-900 p-1 rounded opacity-50 cursor-not-allowed"
                            title="配置功能暂时禁用"
                          >
                            <Settings className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => {
                              setSelectedTopic(topic.name)
                              setShowDeleteModal(true)
                            }}
                            disabled={true}
                            className="text-red-600 hover:text-red-900 p-1 rounded opacity-50 cursor-not-allowed"
                            title="删除功能暂时禁用"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>

              {/* 分页控件 */}
              {filteredTopics.length > pageSize && (
                <div className="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
                  <div className="text-sm text-gray-500">
                    显示 {startIndex + 1} - {Math.min(endIndex, filteredTopics.length)} 条，共 {filteredTopics.length} 条
                  </div>

                  <div className="flex items-center space-x-2">
                    <button
                      onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                      disabled={currentPage === 1}
                      className="px-3 py-1 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      上一页
                    </button>

                    <div className="flex items-center space-x-1">
                      {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                        let pageNum
                        if (totalPages <= 5) {
                          pageNum = i + 1
                        } else if (currentPage <= 3) {
                          pageNum = i + 1
                        } else if (currentPage >= totalPages - 2) {
                          pageNum = totalPages - 4 + i
                        } else {
                          pageNum = currentPage - 2 + i
                        }

                        return (
                          <button
                            key={pageNum}
                            onClick={() => setCurrentPage(pageNum)}
                            className={`px-3 py-1 text-sm border rounded-md ${
                              currentPage === pageNum
                                ? 'bg-blue-500 text-white border-blue-500'
                                : 'border-gray-300 hover:bg-gray-50'
                            }`}
                          >
                            {pageNum}
                          </button>
                        )
                      })}
                    </div>

                    <button
                      onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                      disabled={currentPage === totalPages}
                      className="px-3 py-1 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      下一页
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

      {/* 创建Topic模态框 */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
          <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div className="mt-3">
              <h3 className="text-lg font-medium text-gray-900 mb-4">创建新Topic</h3>

              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Topic名称
                  </label>
                  <input
                    type="text"
                    value={createForm.name}
                    onChange={(e) => setCreateForm({...createForm, name: e.target.value})}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="输入Topic名称"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    分区数
                  </label>
                  <input
                    type="number"
                    min="1"
                    value={createForm.partitions}
                    onChange={(e) => setCreateForm({...createForm, partitions: parseInt(e.target.value) || 1})}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    副本数
                  </label>
                  <input
                    type="number"
                    min="1"
                    max={brokerCount}
                    value={createForm.replication_factor}
                    onChange={(e) => setCreateForm({...createForm, replication_factor: parseInt(e.target.value) || 1})}
                    className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                      createForm.replication_factor > brokerCount
                        ? 'border-red-300 bg-red-50'
                        : 'border-gray-300'
                    }`}
                  />
                  <div className="mt-1 text-xs text-gray-500">
                    当前集群有 {brokerCount} 个broker
                    {createForm.replication_factor > brokerCount && (
                      <div className="text-red-600 mt-1 flex items-center">
                        <AlertCircle className="w-3 h-3 mr-1" />
                        副本数不能大于broker数量
                      </div>
                    )}
                  </div>
                </div>
              </div>

              <div className="flex justify-end gap-3 mt-6">
                <button
                  onClick={() => setShowCreateModal(false)}
                  className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md"
                >
                  取消
                </button>
                <button
                  onClick={createTopic}
                  disabled={!createForm.name.trim() || createForm.replication_factor > brokerCount}
                  className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  创建
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 配置编辑模态框 */}
      {showConfigModal && selectedTopicConfig && (
        <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
          <div className="relative top-10 mx-auto p-5 border w-[800px] max-h-[90vh] shadow-lg rounded-md bg-white overflow-y-auto">
            <div className="mt-3">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-medium text-gray-900 flex items-center gap-2">
                  <Settings className="w-5 h-5 text-blue-600" />
                  Topic配置 - {selectedTopicConfig.name}
                  {isEditingConfig && <span className="text-sm text-orange-600 ml-2">(编辑模式)</span>}
                </h3>
                <button
                  onClick={closeConfigModal}
                  className="text-gray-400 hover:text-gray-600"
                >
                  ×
                </button>
              </div>

              <div className="space-y-4">
                {/* 基本信息 */}
                <div className="bg-gray-50 p-4 rounded-md">
                  <h4 className="text-sm font-medium text-gray-900 mb-3">基本信息</h4>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-gray-500">Topic名称:</span>
                      <span className="ml-2 font-medium">{selectedTopicConfig.name}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">分区数:</span>
                      <span className="ml-2 font-medium">{selectedTopicConfig.partitions}</span>
                    </div>
                    <div>
                      <span className="text-gray-500">副本数:</span>
                      <span className="ml-2 font-medium">{selectedTopicConfig.replication_factor}</span>
                    </div>
                  </div>
                </div>

                {/* 配置参数 */}
                <div className="bg-gray-50 p-4 rounded-md">
                  <div className="flex items-center justify-between mb-3">
                    <h4 className="text-sm font-medium text-gray-900">配置参数</h4>
                    {!isEditingConfig && (
                      <button
                        onClick={() => setIsEditingConfig(true)}
                        className="text-sm text-blue-600 hover:text-blue-800 flex items-center gap-1"
                      >
                        <Edit className="w-3 h-3" />
                        编辑配置
                      </button>
                    )}
                  </div>

                  {/* 配置限制提示 */}
                  <div className="mb-4 bg-yellow-50 border border-yellow-200 rounded-md p-3">
                    <div className="flex">
                      <AlertCircle className="w-4 h-4 text-yellow-400 mr-2 flex-shrink-0 mt-0.5" />
                      <div className="text-xs text-yellow-700">
                        <p className="font-medium mb-2">配置功能说明</p>
                        <p className="mb-2">当前环境限制，显示的是参考配置值。要查看真实配置，请使用：</p>
                        <div className="bg-gray-900 text-green-400 p-2 rounded text-xs font-mono mb-2">
                          <code>kafka-configs.sh --bootstrap-server 192.168.37.11:9092 --entity-type topics --entity-name {selectedTopicConfig?.name} --describe</code>
                        </div>
                        <p>配置编辑功能会提供完整的更新命令。</p>
                      </div>
                    </div>
                  </div>

                  {/* 配置错误提示 */}
                  {configError && (
                    <div className="mb-4 bg-red-50 border border-red-200 rounded-md p-4">
                      <div className="flex">
                        <AlertCircle className="w-5 h-5 text-red-400 mr-3 flex-shrink-0 mt-0.5" />
                        <div className="flex-1">
                          {typeof configError === 'object' ? (
                            <div className="text-sm text-red-700">
                              <h4 className="font-medium mb-2">{configError.error || '配置更新失败'}</h4>
                              <p className="mb-3">{configError.message}</p>

                              {configError.reason && (
                                <p className="mb-3"><strong>原因：</strong>{configError.reason}</p>
                              )}

                              {configError.solution && (
                                <p className="mb-3"><strong>解决方案：</strong>{configError.solution}</p>
                              )}

                              {configError.command && (
                                <div className="mb-3">
                                  <p className="font-medium mb-2">命令行工具：</p>
                                  <div className="bg-gray-900 text-green-400 p-3 rounded text-xs font-mono overflow-x-auto">
                                    <code>{configError.command}</code>
                                  </div>
                                  <button
                                    onClick={() => navigator.clipboard.writeText(configError.command)}
                                    className="mt-2 text-xs text-blue-600 hover:text-blue-800"
                                  >
                                    复制命令
                                  </button>
                                </div>
                              )}

                              {configError.steps && (
                                <div>
                                  <p className="font-medium mb-2">操作步骤：</p>
                                  <ol className="list-decimal list-inside space-y-1 text-xs">
                                    {configError.steps.map((step: string, index: number) => (
                                      <li key={index}>{step}</li>
                                    ))}
                                  </ol>
                                </div>
                              )}
                            </div>
                          ) : (
                            <div className="text-sm text-red-700">
                              <h4 className="font-medium mb-2">配置更新失败</h4>
                              <p>{configError}</p>
                            </div>
                          )}

                          <button
                            onClick={() => setConfigError(null)}
                            className="mt-3 text-xs text-red-600 hover:text-red-800"
                          >
                            关闭错误提示
                          </button>
                        </div>
                      </div>
                    </div>
                  )}

                  {isEditingConfig ? (
                    /* 配置编辑表单 */
                    <div className="space-y-4 max-h-96 overflow-y-auto">
                      <div className="grid grid-cols-2 gap-4">
                        {/* 清理策略 */}
                        <div>
                          <label className="block text-xs font-medium text-gray-700 mb-1">
                            清理策略 (cleanup.policy)
                          </label>
                          <select
                            value={configForm.cleanup_policy}
                            onChange={(e) => setConfigForm({...configForm, cleanup_policy: e.target.value})}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                          >
                            <option value="delete">delete - 删除旧消息</option>
                            <option value="compact">compact - 压缩日志</option>
                            <option value="compact,delete">compact,delete - 压缩并删除</option>
                          </select>
                        </div>

                        {/* 压缩类型 */}
                        <div>
                          <label className="block text-xs font-medium text-gray-700 mb-1">
                            压缩类型 (compression.type)
                          </label>
                          <select
                            value={configForm.compression_type}
                            onChange={(e) => setConfigForm({...configForm, compression_type: e.target.value})}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                          >
                            <option value="producer">producer - 使用生产者压缩</option>
                            <option value="uncompressed">uncompressed - 不压缩</option>
                            <option value="snappy">snappy - Snappy压缩</option>
                            <option value="lz4">lz4 - LZ4压缩</option>
                            <option value="gzip">gzip - GZIP压缩</option>
                            <option value="zstd">zstd - ZSTD压缩</option>
                          </select>
                        </div>

                        {/* 消息保留时间 */}
                        <div>
                          <label className="block text-xs font-medium text-gray-700 mb-1">
                            消息保留时间 (retention.ms)
                          </label>
                          <input
                            type="number"
                            value={configForm.retention_ms}
                            onChange={(e) => setConfigForm({...configForm, retention_ms: e.target.value})}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                            placeholder="毫秒，-1表示无限制"
                          />
                          <p className="text-xs text-gray-500 mt-1">当前: {formatTime(configForm.retention_ms)}</p>
                        </div>

                        {/* 消息保留大小 */}
                        <div>
                          <label className="block text-xs font-medium text-gray-700 mb-1">
                            消息保留大小 (retention.bytes)
                          </label>
                          <input
                            type="number"
                            value={configForm.retention_bytes}
                            onChange={(e) => setConfigForm({...configForm, retention_bytes: e.target.value})}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                            placeholder="字节，-1表示无限制"
                          />
                          <p className="text-xs text-gray-500 mt-1">当前: {formatConfigBytes(configForm.retention_bytes)}</p>
                        </div>

                        {/* 段文件时间 */}
                        <div>
                          <label className="block text-xs font-medium text-gray-700 mb-1">
                            段文件滚动时间 (segment.ms)
                          </label>
                          <input
                            type="number"
                            value={configForm.segment_ms}
                            onChange={(e) => setConfigForm({...configForm, segment_ms: e.target.value})}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                            placeholder="毫秒"
                          />
                          <p className="text-xs text-gray-500 mt-1">当前: {formatTime(configForm.segment_ms)}</p>
                        </div>

                        {/* 段文件大小 */}
                        <div>
                          <label className="block text-xs font-medium text-gray-700 mb-1">
                            段文件大小 (segment.bytes)
                          </label>
                          <input
                            type="number"
                            value={configForm.segment_bytes}
                            onChange={(e) => setConfigForm({...configForm, segment_bytes: e.target.value})}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                            placeholder="字节"
                          />
                          <p className="text-xs text-gray-500 mt-1">当前: {formatConfigBytes(configForm.segment_bytes)}</p>
                        </div>

                        {/* 最大消息大小 */}
                        <div>
                          <label className="block text-xs font-medium text-gray-700 mb-1">
                            最大消息大小 (max.message.bytes)
                          </label>
                          <input
                            type="number"
                            value={configForm.max_message_bytes}
                            onChange={(e) => setConfigForm({...configForm, max_message_bytes: e.target.value})}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                            placeholder="字节"
                          />
                          <p className="text-xs text-gray-500 mt-1">当前: {formatConfigBytes(configForm.max_message_bytes)}</p>
                        </div>

                        {/* 最小同步副本数 */}
                        <div>
                          <label className="block text-xs font-medium text-gray-700 mb-1">
                            最小同步副本数 (min.insync.replicas)
                          </label>
                          <input
                            type="number"
                            min="1"
                            value={configForm.min_insync_replicas}
                            onChange={(e) => setConfigForm({...configForm, min_insync_replicas: e.target.value})}
                            className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                          />
                        </div>
                      </div>

                      {/* 高级配置 */}
                      <div className="border-t pt-4">
                        <h5 className="text-xs font-medium text-gray-900 mb-3">高级配置</h5>
                        <div className="grid grid-cols-2 gap-4">
                          {/* 删除保留时间 */}
                          <div>
                            <label className="block text-xs font-medium text-gray-700 mb-1">
                              删除保留时间 (delete.retention.ms)
                            </label>
                            <input
                              type="number"
                              value={configForm.delete_retention_ms}
                              onChange={(e) => setConfigForm({...configForm, delete_retention_ms: e.target.value})}
                              className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                            />
                            <p className="text-xs text-gray-500 mt-1">当前: {formatTime(configForm.delete_retention_ms)}</p>
                          </div>

                          {/* 消息时间戳类型 */}
                          <div>
                            <label className="block text-xs font-medium text-gray-700 mb-1">
                              消息时间戳类型 (message.timestamp.type)
                            </label>
                            <select
                              value={configForm.message_timestamp_type}
                              onChange={(e) => setConfigForm({...configForm, message_timestamp_type: e.target.value})}
                              className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                            >
                              <option value="CreateTime">CreateTime - 创建时间</option>
                              <option value="LogAppendTime">LogAppendTime - 日志追加时间</option>
                            </select>
                          </div>

                          {/* 布尔配置 */}
                          <div className="col-span-2">
                            <div className="space-y-2">
                              <label className="flex items-center">
                                <input
                                  type="checkbox"
                                  checked={configForm.preallocate}
                                  onChange={(e) => setConfigForm({...configForm, preallocate: e.target.checked})}
                                  className="mr-2"
                                />
                                <span className="text-xs">预分配文件 (preallocate)</span>
                              </label>
                              <label className="flex items-center">
                                <input
                                  type="checkbox"
                                  checked={configForm.unclean_leader_election_enable}
                                  onChange={(e) => setConfigForm({...configForm, unclean_leader_election_enable: e.target.checked})}
                                  className="mr-2"
                                />
                                <span className="text-xs">允许不洁净的Leader选举 (unclean.leader.election.enable)</span>
                              </label>
                              <label className="flex items-center">
                                <input
                                  type="checkbox"
                                  checked={configForm.message_downconversion_enable}
                                  onChange={(e) => setConfigForm({...configForm, message_downconversion_enable: e.target.checked})}
                                  className="mr-2"
                                />
                                <span className="text-xs">启用消息降级转换 (message.downconversion.enable)</span>
                              </label>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  ) : (
                    /* 配置显示模式 */
                    <div className="space-y-2 text-sm max-h-96 overflow-y-auto">
                      <div className="grid grid-cols-2 gap-4">
                        <div className="flex justify-between">
                          <span className="text-gray-500">清理策略:</span>
                          <span className="font-medium">{configForm.cleanup_policy}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-500">压缩类型:</span>
                          <span className="font-medium">{configForm.compression_type}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-500">消息保留时间:</span>
                          <span className="font-medium">{formatTime(configForm.retention_ms)}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-500">消息保留大小:</span>
                          <span className="font-medium">{formatConfigBytes(configForm.retention_bytes)}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-500">段文件时间:</span>
                          <span className="font-medium">{formatTime(configForm.segment_ms)}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-500">段文件大小:</span>
                          <span className="font-medium">{formatConfigBytes(configForm.segment_bytes)}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-500">最大消息大小:</span>
                          <span className="font-medium">{formatConfigBytes(configForm.max_message_bytes)}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-500">最小同步副本:</span>
                          <span className="font-medium">{configForm.min_insync_replicas}</span>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              <div className="flex justify-end gap-3 mt-6">
                {isEditingConfig ? (
                  <>
                    <button
                      onClick={() => {
                        setIsEditingConfig(false)
                        setConfigError(null)
                      }}
                      className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md"
                    >
                      取消
                    </button>
                    <button
                      onClick={updateTopicConfig}
                      className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md"
                    >
                      保存配置
                    </button>
                  </>
                ) : (
                  <>
                    <button
                      onClick={closeConfigModal}
                      className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md"
                    >
                      关闭
                    </button>
                    <button
                      onClick={() => setIsEditingConfig(true)}
                      className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md"
                    >
                      编辑配置
                    </button>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 删除确认模态框 */}
      {showDeleteModal && selectedTopic && (
        <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
          <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div className="mt-3">
              <div className="flex items-center mb-4">
                <AlertCircle className="w-6 h-6 text-red-600 mr-3" />
                <h3 className="text-lg font-medium text-gray-900">确认删除</h3>
              </div>

              <p className="text-sm text-gray-500 mb-6">
                确定要删除Topic "<span className="font-medium text-gray-900">{selectedTopic}</span>" 吗？
                此操作不可撤销，所有相关数据将被永久删除。
              </p>

              <div className="flex justify-end gap-3">
                <button
                  onClick={() => {
                    setShowDeleteModal(false)
                    setSelectedTopic(null)
                  }}
                  className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md"
                >
                  取消
                </button>
                <button
                  onClick={() => deleteTopic(selectedTopic)}
                  className="px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-md"
                >
                  删除
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default TopicManager
